using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using WPFTemplateLib.CustomKeyboard;

namespace WPFTemplateLib.Attached
{
	/// <summary>
	/// TextBox 附加属性帮助类
	/// </summary>
	public class TextBoxAttached : DependencyObject
    {
		#region [附加属性] 键盘窗口类型
		public static Type GetKeyboardWindowType(DependencyObject obj)
		{
			return (Type)obj.GetValue(KeyboardWindowTypeProperty);
		}
		/// <summary>
		/// 键盘窗口类型
		/// </summary>
		public static void SetKeyboardWindowType(DependencyObject obj, Type value)
		{
			obj.SetValue(KeyboardWindowTypeProperty, value);
		}
		/// <summary>
		/// [附加属性] 键盘窗口类型
		/// </summary>
		public static readonly DependencyProperty KeyboardWindowTypeProperty =
			DependencyProperty.RegisterAttached("KeyboardWindowType", typeof(Type), typeof(TextBoxAttached), new PropertyMetadata(typeof(NumberKeyboard)));
		#endregion

		#region [附加属性] 是否使用自定义键盘

		public static bool GetIsUseCustomKeyboard(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsUseCustomKeyboardProperty);
        }
		/// <summary>
		/// 是否使用自定义键盘
		/// </summary>
		public static void SetIsUseCustomKeyboard(DependencyObject obj, bool value)
        {
            obj.SetValue(IsUseCustomKeyboardProperty, value);
        }
		/// <summary>
		/// 是否使用自定义键盘
		/// </summary>
		public static readonly DependencyProperty IsUseCustomKeyboardProperty =
            DependencyProperty.RegisterAttached("IsUseCustomKeyboard", typeof(bool), typeof(TextBoxAttached), new PropertyMetadata(false, OnIsUseCustomKeyboardChanged));

        private static void OnIsUseCustomKeyboardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as TextBox;
            if (target == null) return;

			if ((bool)e.NewValue)
            {
                target.PreviewMouseLeftButtonDown += UseCustomKeyboard_PreviewMouseLeftButtonDown;
            }
            else
            {
                target.PreviewMouseLeftButtonDown -= UseCustomKeyboard_PreviewMouseLeftButtonDown;
            }
        }

        private static void UseCustomKeyboard_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var tb = sender as TextBox;
			if(tb == null) return;

			string originValue = tb.Text;
			Type keyboardWindowType = GetKeyboardWindowType(tb);
			CustomKeyboardHelper.ShowCustomKeyboard(keyboardWindowType, originValue, newValue =>
			{
				tb.Text = newValue;
			});
		}

		#endregion
	}
}
